"""
A dedicated helper to manage templates and prompt building.
"""

import json
import os.path as osp
from typing import Union


class Prompter(object):
    __slots__ = ("template", "_verbose")

    def __init__(self, template_path: str = "", verbose: bool = False):
        self._verbose = verbose
        if not osp.exists(template_path):
            raise ValueError(f"Can't read {template_path}")
        with open(template_path) as fp:
            self.template = json.load(fp)
        if self._verbose:
            print(
                f"Using prompt template {template_path}: {self.template['description']}"
            )

    def generate_prompt(
        self,
        instruction: str,
    ) -> str:
        res = self.template["prompt"].format(instruction=instruction)
        return res

    def get_response(self, output: str) -> str:
        return output.split(self.template["response_split"])[1].strip()